package top.xcxdl.rural.service.impl;

import com.aliyun.oss.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import top.xcxdl.rural.entity.RuralCourse;
import top.xcxdl.rural.entity.RuralUser;
import top.xcxdl.rural.mapper.RuralCourseMapper;
import top.xcxdl.rural.service.IRuralCourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.xcxdl.rural.utils.ImageAddress;

import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Ding
 * @since 2022-05-08
 */
@Service
public class RuralCourseServiceImpl extends ServiceImpl<RuralCourseMapper, RuralCourse> implements IRuralCourseService {

    /**
     * 满完成率
     */
    private final static Integer FINISH_CODE = 100;

    private static final Integer CHAPTER_TYPE = 1;

    private static final Integer LESSON_TYPE = 2;

    @Override
    public PageInfo<RuralCourse> getList(Integer pageNo, Integer pageSize, String key) {
        PageHelper.startPage(pageNo, pageSize);
        List<RuralCourse> list = baseMapper.getList(key);
        // 将图片地址替换为绝对地址
        list.forEach(item -> {
            item.setCourseResourceUrl(ImageAddress.getAllPath(item.getCourseResourceUrl()));
        });
        return new PageInfo<>(list);
    }

    @Override
    public RuralCourse getDetail(Integer courseId) {
        RuralCourse course = baseMapper.getById(courseId);
        if (course != null) {
            course.setCourseResourceUrl(ImageAddress.getAllPath(course.getCourseResourceUrl()));
        }
        return course;
    }

    @Override
    public List<RuralCourse> getChapterAndLessons(Integer courseId) {
        return baseMapper.getChapterAndLessons(courseId);
    }

    @Override
    public int doEdit(RuralCourse course) {
        course.setUpdateTime(String.valueOf(System.currentTimeMillis() / 1000));
        if (course.getCourseId() == null) {
            course.setCreateTime(String.valueOf(System.currentTimeMillis() / 1000));
            return baseMapper.insert(course);
        } else {
            return baseMapper.updateById(course) + 1;
        }
    }

    @Override
    public int doDelete(List<Integer> ids) {
        int ret = 0;
        for (Integer id : ids) {
            //咱也不知道这是几级，所以直接遍历子节点
            int real = 0;
            //获取所有子节点id
            List<Integer> allIDs = baseMapper.getDelIdIgnoreThisId(id);
            //把本体也添加进去
            allIDs.add(id);
            //再联系库，把这些ID删除，并返回删除数量
            real += baseMapper.menuItemDel(allIDs);
            //往回返回
            ret += real;
        }
        return ret;
    }

    @Override
    public PageInfo<RuralCourse> getListByUser(Integer pageNo, Integer pageSize, Integer userId, String key) {
        PageHelper.startPage(pageNo, pageSize);
        List<RuralCourse> list = baseMapper.getListByUser(userId, key);
        // 将图片地址替换为绝对地址
        list.forEach(item -> {
            item.setCourseResourceUrl(ImageAddress.getAllPath(item.getCourseResourceUrl()));
        });
        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<RuralCourse> getCourseListWhereCollected(Integer pageNo, Integer pageSize, Integer userId, String key) {
        PageHelper.startPage(pageNo, pageSize);
        List<RuralCourse> list = baseMapper.getCourseListWhereCollected(userId, key);
        // 做json逻辑处理（不需再次连接数据库）
        list.forEach(item -> {
            //获取当前课程下所有的章节和课节实体，取出完成情况比率，再乘以100后转整型：如83
            final AtomicInteger pass = new AtomicInteger(0);
            int total = item.getChildren().size();
            item.getChildren().forEach(it -> {
                if (it.getIsPass() == 1) {
                    pass.set(pass.get() + 1);
                }
            });
            int completionRate = (int) ((1.0 * pass.get() / total) * 100);
            item.setCompletionRate(completionRate);
            //数据一致筛查，如果完成率为100，但课程状态为未完成，则改为已完成
            if (completionRate == FINISH_CODE && item.getIsPass() == 0) {
                item.setIsPass(1);
                baseMapper.updateCourseUserByCourse(item);
            }
            //反向筛查，目的是怕课程加课，原本完成了，但是课程体系发生改变，所以改为未完成
            if (completionRate < FINISH_CODE && item.getIsPass() == 1) {
                item.setIsPass(0);
                baseMapper.updateCourseUserByCourse(item);
            }
            //将图片地址替换为绝对地址
            item.setCourseResourceUrl(ImageAddress.getAllPath(item.getCourseResourceUrl()));
            //删除处理前的原数据
            item.setChildren(null);
            item.setTemp1(null);
        });
        return new PageInfo<>(list);
    }

    @Override
    public RuralCourse getDetailByUser(Integer courseId, Integer userId) {
        //获取原始数据
        RuralCourse course = baseMapper.getDetailByUser(courseId, userId);
        //初始化该课程的通过数、总数为0，并直接获取章节数、初始化课节数为0
        final AtomicInteger pass = new AtomicInteger(0);
        final AtomicInteger total = new AtomicInteger(0);
        course.setChapterNums(course.getChildren().size());
        course.setLessonNums(0);
        course.getChildren().forEach(item -> {
            //总数++，如果通过，则通过数++，并累加课节数
            total.set(total.get() + 1);
            pass.set(item.getIsPass() == 1 ? (pass.get() + 1) : pass.get());
            course.setLessonNums(item.getChildren().size() + course.getLessonNums());
            //创建临时计数，用于计算章节完成率
            final AtomicInteger passTemp = new AtomicInteger(0);
            final AtomicInteger totalTemp = new AtomicInteger(0);
            //遍历章节下的课节
            item.getChildren().forEach(it -> {
                //总数++，如果通过，则通过数++
                total.set(total.get() + 1);
                totalTemp.set(totalTemp.get() + 1);
                pass.set(it.getIsPass() == 1 ? (pass.get() + 1) : pass.get());
                passTemp.set(it.getIsPass() == 1 ? (passTemp.get() + 1) : passTemp.get());
                //将图片地址替换为绝对地址
                it.setCourseResourceUrl(ImageAddress.getAllPath(it.getCourseResourceUrl()));
                //删除临时变量
                it.setTemp1(null);
            });
            //计算并插入章节完成率
            int completionRateTemp = (int) ((1.0 * passTemp.get() / totalTemp.get()) * 100);
            item.setCompletionRate(completionRateTemp);
            //数据一致筛查，如果章节下课节完成率为100，但章节状态为未完成，则改为已完成
            if (completionRateTemp == FINISH_CODE && item.getIsPass() == 0) {
                item.setIsPass(1);
                //因为一开始判断未完成，没加，所以这里加上
                pass.set(pass.get() + 1);
                baseMapper.updateCourseUserByCourse(item);
            }
            //反向筛查，目的是怕章节内加课，原本完成了，但是课程体系发生改变，所以改为未完成
            if (completionRateTemp < FINISH_CODE && item.getIsPass() == 1) {
                item.setIsPass(0);
                //因为一开始判断已完成，加1，所以这里减去
                pass.set(pass.get() - 1);
                baseMapper.updateCourseUserByCourse(item);
            }
            //删除临时变量
            item.setTemp1(null);
        });
        //将图片地址替换为绝对地址
        course.setCourseResourceUrl(ImageAddress.getAllPath(course.getCourseResourceUrl()));
        //删除临时变量
        course.setTemp1(null);
        //计算并插入总完成率
        int completionRate = (int) ((1.0 * pass.get() / total.get()) * 100);
        course.setCompletionRate(completionRate);
        //数据一致筛查，如果完成率为100，但课程状态为未完成，则改为已完成
        if (completionRate == FINISH_CODE && course.getIsPass() == 0) {
            course.setIsPass(1);
            baseMapper.updateCourseUserByCourse(course);
        }
        //反向筛查，目的是怕课程加课，原本完成了，但是课程体系发生改变，所以改为未完成
        if (completionRate < FINISH_CODE && course.getIsPass() == 1) {
            course.setIsPass(0);
            baseMapper.updateCourseUserByCourse(course);
        }
        return course;
    }

    @Override
    public RuralCourse getInfo(Integer courseId) {
        //获取原始数据
        RuralCourse course = baseMapper.getInfo(courseId);
        //把sons也就是课程类型拆分成数组，再转化成list
        String[] sons = StringUtils.isNullOrEmpty(course.getSons()) ? new String[0] : course.getSons().split(",");
        List<String> sonList = Arrays.asList(sons);
        final AtomicInteger chaptersNum = new AtomicInteger(0);
        final AtomicInteger lessonsNum = new AtomicInteger(0);
        sonList.forEach(item -> {
            if (CHAPTER_TYPE == Integer.parseInt(item)) {
                chaptersNum.set(chaptersNum.get() + 1);
            } else {
                lessonsNum.set(lessonsNum.get() + 1);
            }
        });
        course.setChapterNums(chaptersNum.get());
        course.setLessonNums(lessonsNum.get());
        //将图片地址替换为绝对地址
        course.setCourseResourceUrl(ImageAddress.getAllPath(course.getCourseResourceUrl()));
        //删除临时变量
        course.setSons(null);
        return course;
    }

    @Override
    public List<RuralCourse> getCourseListBySearch(String key) {
        QueryWrapper<RuralCourse> wrapper = new QueryWrapper<>();
        wrapper.like("course_name", key);
        return baseMapper.selectList(wrapper);
    }
}
